﻿using Domain.Material_Management;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Production_Modules.GroupInventory;
using MES.Server.API.Dto.Warehouse;
using ReturnValue;

namespace MES.Server.API.Application.Handler.Production_Modules.GroupInventory
{
    public class GetGroupOutInHander : IRequestHandler<GetGroupOutInCommand, ApiPaging<GetGroupOutInOutPut>>
    {
        private readonly IRepository<GroupOutInModel> groupOutInRepo;
        private readonly IRepository<MaterialGroupModel> materialGroupRepo;
        public GetGroupOutInHander(IRepository<GroupOutInModel> groupOutInRepo, IRepository<MaterialGroupModel> materialGroupRepo)
        {
            this.groupOutInRepo = groupOutInRepo;
            this.materialGroupRepo = materialGroupRepo;
        }
        /// <summary>
        /// 群组出库入库记录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiPaging<GetGroupOutInOutPut>> Handle(GetGroupOutInCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<GetGroupOutInOutPut>();
            var groupOutIn = groupOutInRepo.GetAll();
            var materialGroup = materialGroupRepo.GetAll();
            var linq = from g in groupOutIn
                       join m in materialGroup on g.MaterialGroupId equals m.Id
                       select new GetGroupOutInOutPut
                       {

                                Id = g.Id,
                                OutInCode = g.OutInCode,
                                OutIn = g.OutIn,
                                OutInCount = g.OutInCount,
                           MaterialGroupId = m.Id,
                                MaterialGroupCode = m.MaterialGroupCode,
                                MaterialGroupName = m.MaterialGroupName,
                                CreaterPeople = g.CreaterPeople,
                                CreateTime = g.CreateTime,

                       };
            if (request.OutIn != null)
            {
                linq = linq.Where(x => x.OutIn == request.OutIn);
            }
            if (!string.IsNullOrEmpty(request.MaterialGroupName))
            {
                linq = linq.Where(x => x.MaterialGroupName.Contains(request.MaterialGroupName));
            }
            result.TotalPage = linq.OrderByDescending(x=>x.CreateTime). Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Totalcount = linq.Count();
            result.Code = StatusCode.Success;
            return Task.FromResult(result);
        }
    }
}
